package com.bmadmin.util;

import java.io.File;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * Created by SEELE on 2017/11/28.
 */
public class Util {


	/**
	 * 判断是否为空值
	 * @param str
	 * @return
	 */
	public static boolean isNotNull(String str){
		boolean app = true;
		if(str==null||"".equals(str)||"null".equals(str)){
			app = false;
		}
		return app;
	}

	/**
	 * 把null转换成空字符串
	 */
	public static String NulltoString(Object o) {
		if (o == null)
			return "";
		return o.toString();
	}

	/**
	 * 把json转换成map
	 */
	public static Map jsonToMap(String str) {
		ObjectMapper jsckson = new ObjectMapper();
		Map map=new HashMap();
		try {
			map=  jsckson.readValue(str,Map.class);
		} catch (Exception e1) {

		}
		return map;
	}

	/**
	 * 把json转换成list
	 */
	public static List jsonToList(String str) {
		ObjectMapper jsckson = new ObjectMapper();
		List<Map> list=new ArrayList();
		try {
			list = jsckson.readValue(str,ArrayList.class);
		} catch (Exception e1) {

		}
		return list;
	}

	/**
	 * 把map转换成json
	 */
	public static String mapToJson(Map map) {
		ObjectMapper jsckson = new ObjectMapper();
		String ret="";
		try {
			ret= jsckson.writeValueAsString(map);
		} catch (Exception e1) {

		}
		return ret;
	}

	/**
	 * 把list转换成json
	 */
	public static String listToJson(List list) {
		ObjectMapper jsckson = new ObjectMapper();
		String ret="";
		try {
			ret= jsckson.writeValueAsString(list);
		} catch (Exception e1) {

		}
		return ret;
	}

	/**
	 * ResultSet转换成List
	 */
	public List resultSetToList(ResultSet rs) throws java.sql.SQLException {
		if (rs == null)
			return Collections.EMPTY_LIST;
		ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息，比如字段数、字段名等
		int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数
		List list = new ArrayList();
		Map rowData = new HashMap();
		while (rs.next()) {
			rowData = new HashMap(columnCount);
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
		}
		return list;
	}

	/**
	 * ResultSet转换成json
	 */
	public static String resultSetToJson(ResultSet rs) throws SQLException,JSONException{
		// json数组
		JSONArray array = new JSONArray();

		// 获取列数
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();

		// 遍历ResultSet中的每条数据
		while (rs.next()) {
			JSONObject jsonObj = new JSONObject();

			// 遍历每一列
			for (int i = 1; i <= columnCount; i++) {
				String columnName =metaData.getColumnLabel(i);
				String value = rs.getString(columnName);
				if(BMUtil.isNullOrEmpty(value)){
					value="-";
				}
				jsonObj.put(columnName, value);
			}
			array.add(jsonObj);
		}

		return array.toString();
	}
	
	/**
	 * 获取反向代理后真实的IP
	 */
	public static String getIPAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if(null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if(null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * lyq 长度16位
	 * 
	 * @return
	 */
	public static String getSn() {
		String rt = "";
		Date dt = new Date();
		SimpleDateFormat date_format = new SimpleDateFormat("yyMMddhhmmss");

		rt = date_format.format(dt);
		rt += getRandmonVerifyCode(4);

		return rt;
	}
	
	/**
	 * 生成制定长度验证码
	 * 
	 * @param verifyCode_len
	 *            验证码长度
	 * @return String
	 */
	private synchronized static String getRandmonVerifyCode(int verifyCode_len) {
		char[] c = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		int maxNum = 100;
		int count = 0;// 记录验证码长度

		StringBuffer verifyCodeStr = new StringBuffer();
		Random random = new Random(System.currentTimeMillis());
		while (count < verifyCode_len) {
			int i = random.nextInt(maxNum);
			if (i >= 0 && i < c.length) {
				verifyCodeStr.append(String.valueOf(i));
				count++;
			}
		}
		return verifyCodeStr.toString();
	}
	
    /**
     * 删除指定文件夹下的所有文件
     */
    public static void deleteDir(String path){
        File file = new File(path);
        if(!file.exists()){//判断是否待删除目录是否存在
            System.err.println("文件夹不存在！");
        }
        String[] content = file.list();//取得当前目录下所有文件和文件夹
        for(String name : content){
            File temp = new File(path, name);
            if(temp.isDirectory()){//判断是否是目录
                deleteDir(temp.getAbsolutePath());//递归调用，删除目录里的内容
                temp.delete();//删除空目录
            }else{
                if(!temp.delete()){//直接删除文件
                    System.err.println("删除" + name + "失败");
                }
            }
        }
        file.delete();
    }
}
